package com.cms.biz.category;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.cms.bean.CategoryBean;
import com.cms.config.CategoryTypeDef;
import com.cms.database.DBHelper;
import com.cms.facade.RequestFacade;
import com.cms.facade.SessionFacade;
import com.cms.framework.Command;
import com.cms.framework.CommandException;
import com.cms.framework.CommandToken;
import com.cms.util.ApplicationHelper;
import com.cms.util.StringHelper;

public class AddCategoryCommand implements Command {
	private String next;
	public AddCategoryCommand(String next) {
		this.next = next;
	}

	@Override
	public String execute(HttpServletRequest req) throws CommandException {
		HttpSession session = req.getSession();
        Connection conn = DBHelper.getConn();
        PreparedStatement pst = null;
        
        try {
        	
			if (!CommandToken.isValid(req)) {
				RequestFacade.setSuccessFlag(req, Boolean.FALSE);
				RequestFacade.setInvalidTokenMsg(req);
				return next;
			}
        	
			String user = SessionFacade.getUser(session);
        	String categoryName = StringHelper.isRequestEmptyString(req, "categoryName", "");
        	int parentId = StringHelper.isRequestParamEmptyInt(req, "parentId", 0);
        	int categoryTypeId = StringHelper.isRequestParamEmptyInt(req, "categoryTypeId", CategoryTypeDef.NEW);
        	pst = conn.prepareStatement(SQLString.ADD_CATEGORY);
        	pst.setString(1, categoryName);
        	pst.setInt(2, categoryTypeId);
        	pst.setInt(3, parentId);
        	pst.setString(4, user);
        	pst.execute();
        	
        	//synchronization
        	List<CategoryBean> list = CategoryHelper.getCategoryListByTypeId(conn, categoryTypeId);
        	ApplicationHelper.setApplicationSubCategoryListById(session, list, categoryTypeId);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			if (pst != null) {
				try {
					pst.close();
					pst = null;
				} catch (final SQLException e) {
				}
			}
			DBHelper.closeConn(conn);
		}		
		return next;
	}

}
